//
//@author jltxseo
// Created by junlintianxia on 2019/5/6.
//

#include "JavaListener.h"
#include <android/log.h>

#define LOG_TAG "ndk.out.c"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

JavaListener::JavaListener(JavaVM *vm, JNIEnv *env, jobject jobj) {
    this->vm = vm;
    this->env = env;
    this->jobj = jobj;

    jclass  jclaz = env->GetObjectClass(jobj);

    jmethod = env->GetStaticMethodID(jclaz,"onSuccess","(Ljava/lang/String;)V");
}

/**
 *  在子线程回调这个方法 onSuccess
 * @param msg
 */
void JavaListener::onSuccess(const char *msg) {
    int  attach;
    JNIEnv *env = JNI_GetEnv(&attach);
    //构造一个jstring对象,将需要传递给 Java 层 onSuccess 的 msg 转化为 jstring 实例
    jstring jmsg = env->NewStringUTF(msg);

    jclass  jclaz = env->GetObjectClass(jobj);

    //调用一个静态的java方法    void        (*CallStaticVoidMethod)(JNIEnv*, jclass, jmethodID, ...);
    env->CallStaticVoidMethod(jclaz,jmethod,jmsg);

    env->DeleteLocalRef(jmsg);

    JNI_DelEnv();
}


JNIEnv * JavaListener::JNI_GetEnv(int *attach) {
    if (vm == NULL)
        return NULL;

    int status;

    //判断是否有AttachCurrentThread
    *attach = 0;

    JNIEnv *_jniEnv = NULL;

    status = vm->GetEnv((void **) &_jniEnv, JNI_VERSION_1_6);

    if (status == JNI_EDETACHED || _jniEnv == NULL) {
        status = vm->AttachCurrentThread(&_jniEnv, NULL);
        if (status < 0) {
            _jniEnv = NULL;
        } else {
            *attach = 1;
        }
    }
    return _jniEnv;
}

int JavaListener::JNI_DelEnv() {
    if (vm == NULL)
        return -1;

    return vm->DetachCurrentThread();
}

